"""
API路由模块
提供RESTful API接口
"""

from typing import List, Dict, Any, Optional
from datetime import datetime
from fastapi import APIRouter, HTTPException, Query, Path, UploadFile, File
from pydantic import BaseModel

from ..core import config, api_logger
from ..storage import DatabaseManager, ExportManager
from .models import *

# 创建路由器
router = APIRouter()

# 全局实例
db_manager = DatabaseManager()
export_manager = ExportManager()


@router.get("/health", response_model=HealthResponse)
async def health_check():
    """健康检查"""
    return HealthResponse(
        status="healthy",
        timestamp=datetime.now(),
        version=config.system.version
    )


@router.get("/meetings", response_model=List[MeetingResponse])
async def get_meetings(
    limit: int = Query(100, ge=1, le=1000),
    offset: int = Query(0, ge=0)
):
    """获取会议列表"""
    try:
        meetings = db_manager.get_meeting_records(limit=limit, offset=offset)
        return [MeetingResponse(**meeting) for meeting in meetings]
    except Exception as e:
        api_logger.error(f"获取会议列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取会议列表失败")


@router.post("/meetings", response_model=MeetingResponse)
async def create_meeting(meeting: CreateMeetingRequest):
    """创建新会议"""
    try:
        success = db_manager.create_meeting(
            meeting_id=meeting.meeting_id,
            title=meeting.title,
            description=meeting.description
        )
        
        if not success:
            raise HTTPException(status_code=400, detail="会议ID已存在")
        
        # 获取创建的会议
        meeting_data = db_manager.get_meeting_by_id(meeting.meeting_id)
        if not meeting_data:
            raise HTTPException(status_code=500, detail="创建会议失败")
        
        return MeetingResponse(**meeting_data)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.error(f"创建会议失败: {e}")
        raise HTTPException(status_code=500, detail="创建会议失败")


@router.get("/meetings/{meeting_id}", response_model=MeetingResponse)
async def get_meeting(meeting_id: str = Path(..., description="会议ID")):
    """获取指定会议信息"""
    try:
        meeting = db_manager.get_meeting_by_id(meeting_id)
        if not meeting:
            raise HTTPException(status_code=404, detail="会议不存在")
        
        return MeetingResponse(**meeting)
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.error(f"获取会议信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取会议信息失败")


@router.put("/meetings/{meeting_id}/status")
async def update_meeting_status(
    meeting_id: str = Path(..., description="会议ID"),
    status_update: UpdateMeetingStatusRequest = None
):
    """更新会议状态"""
    try:
        success = db_manager.update_meeting_status(meeting_id, status_update.status)
        if not success:
            raise HTTPException(status_code=404, detail="会议不存在")
        
        return {"message": "状态更新成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.error(f"更新会议状态失败: {e}")
        raise HTTPException(status_code=500, detail="更新会议状态失败")


@router.delete("/meetings/{meeting_id}")
async def delete_meeting(meeting_id: str = Path(..., description="会议ID")):
    """删除会议"""
    try:
        success = db_manager.delete_meeting(meeting_id)
        if not success:
            raise HTTPException(status_code=404, detail="会议不存在")
        
        return {"message": "会议删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.error(f"删除会议失败: {e}")
        raise HTTPException(status_code=500, detail="删除会议失败")


@router.get("/meetings/{meeting_id}/texts", response_model=List[TextResponse])
async def get_meeting_texts(meeting_id: str = Path(..., description="会议ID")):
    """获取会议的文本记录"""
    try:
        texts = db_manager.get_text_records(meeting_id)
        return [TextResponse(**text) for text in texts]
        
    except Exception as e:
        api_logger.error(f"获取文本记录失败: {e}")
        raise HTTPException(status_code=500, detail="获取文本记录失败")


@router.get("/meetings/{meeting_id}/segments", response_model=List[SegmentResponse])
async def get_meeting_segments(meeting_id: str = Path(..., description="会议ID")):
    """获取会议的段落记录"""
    try:
        segments = db_manager.get_segment_records(meeting_id)
        return [SegmentResponse(**segment) for segment in segments]
        
    except Exception as e:
        api_logger.error(f"获取段落记录失败: {e}")
        raise HTTPException(status_code=500, detail="获取段落记录失败")


@router.get("/search/texts", response_model=List[TextResponse])
async def search_texts(
    meeting_id: Optional[str] = Query(None, description="会议ID"),
    keyword: Optional[str] = Query(None, description="关键词"),
    source_type: Optional[str] = Query(None, description="来源类型"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    limit: int = Query(100, ge=1, le=1000, description="返回数量限制")
):
    """搜索文本记录"""
    try:
        texts = db_manager.search_text_records(
            meeting_id=meeting_id,
            keyword=keyword,
            source_type=source_type,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return [TextResponse(**text) for text in texts]
        
    except Exception as e:
        api_logger.error(f"搜索文本记录失败: {e}")
        raise HTTPException(status_code=500, detail="搜索文本记录失败")


@router.post("/meetings/{meeting_id}/export")
async def export_meeting(
    meeting_id: str = Path(..., description="会议ID"),
    export_request: ExportRequest = None
):
    """导出会议数据"""
    try:
        # 获取会议数据
        meeting = db_manager.get_meeting_by_id(meeting_id)
        if not meeting:
            raise HTTPException(status_code=404, detail="会议不存在")
        
        texts = db_manager.get_text_records(meeting_id)
        segments = db_manager.get_segment_records(meeting_id)
        
        meeting_data = {
            'meeting': meeting,
            'texts': texts,
            'segments': segments
        }
        
        # 执行导出
        results = export_manager.export_meeting(
            meeting_data=meeting_data,
            formats=export_request.formats,
            output_dir=export_request.output_dir
        )
        
        return ExportResponse(
            meeting_id=meeting_id,
            formats=export_request.formats,
            results=results,
            export_time=datetime.now()
        )
        
    except HTTPException:
        raise
    except Exception as e:
        api_logger.error(f"导出会议数据失败: {e}")
        raise HTTPException(status_code=500, detail="导出会议数据失败")


@router.get("/export/formats")
async def get_export_formats():
    """获取支持的导出格式"""
    return {
        "formats": export_manager.get_supported_formats(),
        "descriptions": {
            "markdown": "Markdown格式，适合文档查看",
            "docx": "Word文档格式，适合编辑和打印",
            "json": "JSON格式，适合程序处理"
        }
    }


@router.get("/statistics", response_model=StatisticsResponse)
async def get_statistics():
    """获取系统统计信息"""
    try:
        db_stats = db_manager.get_statistics()
        
        return StatisticsResponse(
            meeting_count=db_stats.get('meeting_count', 0),
            text_count=db_stats.get('text_count', 0),
            segment_count=db_stats.get('segment_count', 0),
            database_url=db_stats.get('database_url', ''),
            system_info={
                "version": config.system.version,
                "debug": config.system.debug,
                "max_workers": config.system.max_workers
            }
        )
        
    except Exception as e:
        api_logger.error(f"获取统计信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取统计信息失败")


@router.get("/config")
async def get_config():
    """获取系统配置信息（敏感信息已过滤）"""
    try:
        safe_config = {
            "system": {
                "name": config.system.name,
                "version": config.system.version,
                "debug": config.system.debug,
                "log_level": config.system.log_level
            },
            "video_input": {
                "max_streams": config.video_input.max_streams,
                "default_fps": config.video_input.default_fps,
                "sampling_rate": config.video_input.sampling_rate,
                "supported_formats": config.video_input.supported_formats
            },
            "yolo_detection": {
                "confidence_threshold": config.yolo_detection.confidence_threshold,
                "iou_threshold": config.yolo_detection.iou_threshold,
                "max_detections_per_frame": config.yolo_detection.max_detections_per_frame,
                "input_size": config.yolo_detection.input_size,
                "device": config.yolo_detection.device
            },
            "ocr": {
                "use_gpu": config.ocr.use_gpu,
                "lang": config.ocr.lang,
                "batch_size": config.ocr.batch_size,
                "confidence_threshold": config.ocr.confidence_threshold
            },
            "export": {
                "formats": config.export.formats,
                "max_export_size": config.export.max_export_size
            }
        }
        
        return safe_config
        
    except Exception as e:
        api_logger.error(f"获取配置信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取配置信息失败")
